<?php

	// 公共助手函数

	if (!function_exists('__')) {

		/**
		 * 获取语言变量值
		 *
		 * @param string $name 语言变量名
		 * @param array  $vars 动态变量值
		 * @param string $lang 语言
		 *
		 * @return mixed
		 */
		function __ ($name, $vars = [], $lang = '') {
			if (is_numeric($name) || !$name) {
				return $name;
			}
			if (!is_array($vars)) {
				$vars = func_get_args();
				array_shift($vars);
				$lang = '';
			}

			return \think\Lang::get($name, $vars, $lang);
		}
	}

	if (!function_exists('format_bytes')) {

		/**
		 * 将字节转换为可读文本
		 *
		 * @param int    $size      大小
		 * @param string $delimiter 分隔符
		 *
		 * @return string
		 */
		function format_bytes ($size, $delimiter = '') {
			$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
			for ($i = 0; $size >= 1024 && $i < 6; $i++) {
				$size /= 1024;
			}

			return round($size, 2) . $delimiter . $units[$i];
		}
	}

	if (!function_exists('datetime')) {

		/**
		 * 将时间戳转换为日期时间
		 *
		 * @param int    $time   时间戳
		 * @param string $format 日期时间格式
		 *
		 * @return string
		 */
		function datetime ($time, $format = 'Y-m-d H:i:s') {
			$time = is_numeric($time) ? $time : strtotime($time);

			return date($format, $time);
		}
	}

	if (!function_exists('human_date')) {

		/**
		 * 获取语义化时间
		 *
		 * @param int $time  时间
		 * @param int $local 本地时间
		 *
		 * @return string
		 */
		function human_date ($time, $local = null) {
			return \fast\Date::human($time, $local);
		}
	}

	if (!function_exists('cdnurl')) {

		/**
		 * 获取上传资源的CDN的地址
		 *
		 * @param string  $url    资源相对地址
		 * @param boolean $domain 是否显示域名 或者直接传入域名
		 *
		 * @return string
		 */
		function cdnurl ($url, $domain = false) {
			$regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
			$url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
			if ($domain && !preg_match($regex, $url)) {
				$domain = is_bool($domain) ? request()->domain() : $domain;
				$url = $domain . $url;
			}

			return $url;
		}
	}

	if (!function_exists('is_really_writable')) {

		/**
		 * 判断文件或文件夹是否可写
		 *
		 * @param    string $file 文件或目录
		 *
		 * @return    bool
		 */
		function is_really_writable ($file) {
			if (DIRECTORY_SEPARATOR === '/') {
				return is_writable($file);
			}
			if (is_dir($file)) {
				$file = rtrim($file, '/') . '/' . md5(mt_rand());
				if (($fp = @fopen($file, 'ab')) === false) {
					return false;
				}
				fclose($fp);
				@chmod($file, 0777);
				@unlink($file);

				return true;
			} elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
				return false;
			}
			fclose($fp);

			return true;
		}
	}

	if (!function_exists('rmdirs')) {

		/**
		 * 删除文件夹
		 *
		 * @param string $dirname  目录
		 * @param bool   $withself 是否删除自身
		 *
		 * @return boolean
		 */
		function rmdirs ($dirname, $withself = true) {
			if (!is_dir($dirname)) {
				return false;
			}
			$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);

			foreach ($files as $fileinfo) {
				$todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
				$todo($fileinfo->getRealPath());
			}
			if ($withself) {
				@rmdir($dirname);
			}

			return true;
		}
	}

	if (!function_exists('copydirs')) {

		/**
		 * 复制文件夹
		 *
		 * @param string $source 源文件夹
		 * @param string $dest   目标文件夹
		 */
		function copydirs ($source, $dest) {
			if (!is_dir($dest)) {
				mkdir($dest, 0755, true);
			}
			foreach ($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item) {
				if ($item->isDir()) {
					$sontDir = $dest . DS . $iterator->getSubPathName();
					if (!is_dir($sontDir)) {
						mkdir($sontDir, 0755, true);
					}
				} else {
					copy($item, $dest . DS . $iterator->getSubPathName());
				}
			}
		}
	}

	if (!function_exists('mb_ucfirst')) {
		function mb_ucfirst ($string) {
			return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
		}
	}

	if (!function_exists('addtion')) {

		/**
		 * 附加关联字段数据
		 *
		 * @param array $items  数据列表
		 * @param mixed $fields 渲染的来源字段
		 *
		 * @return array
		 */
		function addtion ($items, $fields) {
			if (!$items || !$fields) {
				return $items;
			}
			$fieldsArr = [];
			if (!is_array($fields)) {
				$arr = explode(',', $fields);
				foreach ($arr as $k => $v) {
					$fieldsArr[$v] = ['field' => $v];
				}
			} else {
				foreach ($fields as $k => $v) {
					if (is_array($v)) {
						$v['field'] = isset($v['field']) ? $v['field'] : $k;
					} else {
						$v = ['field' => $v];
					}
					$fieldsArr[$v['field']] = $v;
				}
			}
			foreach ($fieldsArr as $k => &$v) {
				$v = is_array($v) ? $v : ['field' => $v];
				$v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
				$v['primary'] = isset($v['primary']) ? $v['primary'] : '';
				$v['column'] = isset($v['column']) ? $v['column'] : 'name';
				$v['model'] = isset($v['model']) ? $v['model'] : '';
				$v['table'] = isset($v['table']) ? $v['table'] : '';
				$v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
			}
			unset($v);
			$ids = [];
			$fields = array_keys($fieldsArr);
			foreach ($items as $k => $v) {
				foreach ($fields as $m => $n) {
					if (isset($v[$n])) {
						$ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
					}
				}
			}
			$result = [];
			foreach ($fieldsArr as $k => $v) {
				if ($v['model']) {
					$model = new $v['model'];
				} else {
					$model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
				}
				$primary = $v['primary'] ? $v['primary'] : $model->getPk();
				$result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
			}

			foreach ($items as $k => &$v) {
				foreach ($fields as $m => $n) {
					if (isset($v[$n])) {
						$curr = array_flip(explode(',', $v[$n]));

						$v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
					}
				}
			}

			return $items;
		}
	}

	if (!function_exists('var_export_short')) {

		/**
		 * 返回打印数组结构
		 *
		 * @param string $var    数组
		 * @param string $indent 缩进字符
		 *
		 * @return string
		 */
		function var_export_short ($var, $indent = "") {
			switch (gettype($var)) {
				case "string":
					return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
				case "array":
					$indexed = array_keys($var) === range(0, count($var) - 1);
					$r = [];
					foreach ($var as $key => $value) {
						$r[] = "$indent    " . ($indexed ? "" : var_export_short($key) . " => ") . var_export_short($value, "$indent    ");
					}

					return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
				case "boolean":
					return $var ? "TRUE" : "FALSE";
				default:
					return var_export($var, true);
			}
		}
	}

	if (!function_exists('letter_avatar')) {
		/**
		 * 首字母头像
		 *
		 * @param $text
		 *
		 * @return string
		 */
		function letter_avatar ($text) {
			$total = unpack('L', hash('adler32', $text, true))[1];
			$hue = $total % 360;
			list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

			$bg = "rgb({$r},{$g},{$b})";
			$color = "#ffffff";
			$first = mb_strtoupper(mb_substr($text, 0, 1));
			$src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
			$value = 'data:image/svg+xml;base64,' . $src;

			return $value;
		}
	}

	if (!function_exists('hsv2rgb')) {
		function hsv2rgb ($h, $s, $v) {
			$r = $g = $b = 0;

			$i = floor($h * 6);
			$f = $h * 6 - $i;
			$p = $v * (1 - $s);
			$q = $v * (1 - $f * $s);
			$t = $v * (1 - (1 - $f) * $s);

			switch ($i % 6) {
				case 0:
					$r = $v;
					$g = $t;
					$b = $p;
					break;
				case 1:
					$r = $q;
					$g = $v;
					$b = $p;
					break;
				case 2:
					$r = $p;
					$g = $v;
					$b = $t;
					break;
				case 3:
					$r = $p;
					$g = $q;
					$b = $v;
					break;
				case 4:
					$r = $t;
					$g = $p;
					$b = $v;
					break;
				case 5:
					$r = $v;
					$g = $p;
					$b = $q;
					break;
			}

			return [
				floor($r * 255),
				floor($g * 255),
				floor($b * 255)
			];
		}
	}


	/****************自定义函数从此开始***********************************/
	if (!function_exists('success')) {
		/**
		 * 请求成功返回数据格式
		 *
		 * @param        $data   返回的数据
		 * @param int    $code   状态码
		 * @param string $msg    提示语
		 *
		 * @return mixed
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function success ($data = [], $code = 1, $msg = '操作成功') {
			$result['code'] = $code;
			$result['msg'] = $msg;
			$result['data'] = $data;

			return $result;
		}
	}


	if (!function_exists('error')) {
		/**
		 * 请求失败返回的数据格式
		 *
		 * @param string $msg    提示语
		 * @param int    $code   状态码
		 * @param string $data   数据(一般为空,注重的是提示语和状态码)
		 *
		 * @return mixed
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function error ($msg = '操作失败', $code = -1, $data = '') {
			$result['code'] = $code;
			$result['msg'] = $msg;
			$result['data'] = $data;

			return $result;
		}
	}

	if (!function_exists('random')) {
		/**
		 * @param $length  需要生成的字符串的长度
		 * @param $numeric 纯数字
		 *
		 * @return null|string  返回字符串
		 */
		function random ($length, $numeric = false) {
			$str = null;
			$mixture = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
			$number = '0123456789';
			$strBase = $numeric ? $number : $mixture;
			$max = strlen($strBase) - 1;

			for ($i = 0; $i < $length; $i++) {
				$str .= $strBase[rand(0, $max)];
			}

			return $str;
		}
	}


	if (!function_exists('https_request')) {
		/**
		 * curl get post请求
		 *
		 * @param      $url
		 * @param null $data
		 *
		 * @return bool|string
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function https_request ($url, $data = null, $header = null) {
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
			if (!empty($data)) {
				curl_setopt($curl, CURLOPT_POST, 1);
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

			if (!empty($header)) {
				curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
			}

			$output = curl_exec($curl);
			curl_close($curl);

			return $output;
		}

	}

	if (!function_exists('ArrToXml')) {
		/**
		 * 数组转换成xml
		 *
		 * @param $arr
		 *
		 * @return bool|string
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function ArrToXml ($arr) {
			if (!is_array($arr) || count($arr) == 0) {
				return false;
			}

			$xml = "<xml>";
			foreach ($arr as $key => $val) {
				if (is_numeric($val)) {
					$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
				} else {
					$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
				}
			}
			$xml .= "</xml>";

			return $xml;
		}
	}

	if (!function_exists('ArrToXml')) {
		/**
		 * xml 转换成数组
		 *
		 * @param $xml
		 *
		 * @return bool|mixed
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function XmlToArr ($xml) {
			if ($xml == '') {
				return false;
			}
			libxml_disable_entity_loader(true);
			$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

			return $arr;
		}
	}

	if (!function_exists('curl_request')) {
		/**
		 * curl请求 携带头部和证书
		 *
		 * @param       $url
		 * @param       $data
		 * @param array $header
		 * @param bool  $sllkey
		 *
		 * @return mixed
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function curl_request ($url, $data, $header = [], $sllkey = false) {
			$curl = curl_init();
			if ($header && $header != []) {
				curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
			}
			if ($sllkey) {
				curl_setopt($curl, CURLOPT_SSLCERT, $this->apiclient_cert);
				curl_setopt($curl, CURLOPT_SSLKEY, $this->apiclient_key);
				curl_setopt($curl, CURLOPT_CAINFO, $this->rootca);
			}
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			$result = curl_exec($curl);
			curl_close($curl);

			return $result;
		}
	}

	if (!function_exists('ArrToUrl')) {
		/**
		 * 数组转换成url格式的字符串,支付生成签名时常用
		 *
		 * @param $arr
		 *
		 * @return string
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function ArrToUrl ($arr) {
			return urldecode(http_build_query($arr));
		}
	}


	if (!function_exists('filterEmoji')) {
		/**
		 * 去除特殊符号入库
		 *
		 * @param $str
		 *
		 * @return null|string|string[]
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function filterEmoji ($str) {
			return preg_replace_callback('/./u', function (array $match) { return strlen($match[0]) >= 4 ? '' : $match[0]; }, $str);
		}
	}


	if (!function_exists('objToArr')) {

		/**
		 * 返回数组
		 *
		 * @param $obj
		 *
		 * @return mixed
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function objToArr ($obj) {
			return json_decode(json_encode($obj), true);
		}

	}


	if (!function_exists('toImages')) {
		/**
		 * @param $data  多张图片
		 *
		 * @return string
		 *
		 * @param
		 *
		 * @throws
		 *
		 */
		function toImages ($data) {
			$request = \think\Request::instance();
			if (is_string($data)) {//处理单张图片
				if (strpos($data, ',') === false) {
					return $request->domain() . $data;
				} else {
					$data = explode(',', $data);
					foreach ($data as &$val) {
						$val = $request->domain() . $val;
					}

					return $data;
				}
			} else if (is_array($data)) {//处理多张图片
				foreach ($data as &$val) {
					$val = $request->domain() . $val;
				}

				return $data;
			}
		}
	}


	if (!function_exists('addErrorLog')) {
		/**
		 * 记录日志
		 * @param null   $data          记录数据
		 * @param string $filename      保存到文件名
		 * @param string $folder        日志目录
		 * @param string $path          更目录
		 * @param
		 * @throws
		 *
		 */
		function addErrorLog($data = '',$filename='index.log',$folder='record' ,$path = RUNTIME_PATH){

			$dir = $path.$folder.'/'.date('Ymd');

			if(!is_dir($dir)){
				mkdir($dir,0777,true);
			}

			$file = $dir.'/'.$filename;
			error_log(date('Y-m-d H:i:s').': '.print_r($data,true)."\r\n",3,$file);

		}
	}



